<script lang="ts">
	import type { ChoiceQuestion } from '$lib/api/proto/resource_exam_type_api';
	import { Trash } from 'lucide-svelte';

	interface Props {
		question: ChoiceQuestion;
		onChange: (question: ChoiceQuestion) => void;
	}
	let props: Props = $props();

	let question = $state(props.question.question);
	let choiceList = $state(props.question.choiceList.slice());

	$effect(() => {
		props.onChange({
			question,
			choiceList
		});
	});
</script>

<div class="space-y-2">
	<label class="label w-full">
		<span class="label w-[100px] text-right inline-block pr-[10px]">问题:</span>
		<input type="text" class="input w-full" bind:value={question} />
	</label>
	<div class="flex justify-between">
		<h4 class="text-lg font-bold">选项</h4>
		<button
			type="button"
			class="btn btn-accent"
			onclick={() => {
				const label = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.substring(
					choiceList.length,
					choiceList.length + 1
				);
				choiceList.push({
					label,
					value: '',
					rightAnswer: false
				});
			}}>增加选项</button
		>
	</div>
	{#each choiceList as choice, index}
		<div class="flex gap-2">
			<input
				type="text"
				class="input w-[50px]"
				value={choice.label}
				onchange={(e) => {
					const tmpList = choiceList.slice();
					tmpList[index].label = e.currentTarget.value.trim();
					choiceList = tmpList;
				}}
			/>
			<input
				type="text"
				class="input w-full"
				value={choice.value}
				onchange={(e) => {
					const tmpList = choiceList.slice();
					tmpList[index].value = e.currentTarget.value.trim();
					choiceList = tmpList;
				}}
			/>
			<label class="label">
				<input
					type="checkbox"
					checked={choice.rightAnswer}
					class="checkbox"
					onchange={(e) => {
						const tmpList = choiceList.slice();
						tmpList[index].rightAnswer = e.currentTarget.checked;
						choiceList = tmpList;
					}}
				/>
				正确答案
			</label>
			<button
				class="btn btn-ghost text-error p-1"
				onclick={() => {
					const tmpList = choiceList.filter((item) => item.label != choice.label);
					choiceList = tmpList;
				}}><Trash /></button
			>
		</div>
	{/each}
</div>
